import Koa from "koa"
import Router from "koa-router"
import bodyParser from "koa-bodyparser"

const app = new Koa()
const router = new Router({
  prefix: "/api/v1"
})
const config = require("./config/server.json")

const { setToken, verifyToken, checkToken } = require("./lib/token")

// console.log("调试用万能 token", setToken("black sheep", 1, 1000))

import { fail, success } from "./lib/result"

/* 配置跨域 */

app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*")
  ctx.set(
    "Access-Control-Allow-Headers",
    "Content-Type, Content-Length, Authorization, Accept, X-Requested-With"
  )
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")
  if (ctx.method == "OPTIONS") {
    ctx.body = 200
  } else {
    await next()
  }
})

app.use(bodyParser())

/* 错误处理 */

app.use(async (ctx, next) => {
  try {
    await next()
    if (parseInt(ctx.status) === 404) {
      ctx.response.body = "owo 电波无法到达哦～"
    }
  } catch (err) {
    ctx.response.status = err.statusCode || err.status || 500
    ctx.response.body = {
      message: err.message
    }
  }
})

/* koa-jwt */
const pathList = [
    "/token",
    "/user",
    "/wx",
    "/article",
    "/label",
    "/mdn",
    "/token2user"
  ],
  regList = []

pathList.forEach(item => {
  regList.push(new RegExp("^/api/v1" + item))
})

console.log("以下路由不需要鉴权：")
console.log(regList)

app.use(
  koaJwt({ secret: config.authorization.jwt }).unless({
    path: regList // /^\/user/
  })
)

/* body-parser */

app.use(bodyParser())

router.all("/", async (ctx, next) => {
  ctx.body = {
    hi: "hello, full-stack-group!",
    author: "Meeken",
    github: "https://github.com/Meeken1998",
    site: "meek3n.cn"
  }
  await next()
})

router
  .get("/article", async (ctx, next) => {
    ctx.body = await require("./controller/article").get(ctx, next)
  })
  .get("/article/:id", async (ctx, next) => {
    ctx.body = await require("./controller/article").get(ctx, next, true)
  })
  .get("/label", async (ctx, next) => {
    ctx.body = await require("./controller/article").getLabelsList(ctx, next)
  })

router
  .get("/meekensocool", async (ctx, next) => {
    ctx.body = success(setToken("username", 10086, 1))
  })
  .get("/token2user", async (ctx, next) => {
    ctx.body = await require("./controller/user").check(ctx, next)
  })

router
  .post("/user", async (ctx, next) => {
    ctx.body = await require("./controller/user").register(ctx, next)
  })
  .post("/login", async (ctx, next) => {
    ctx.body = await require("./controller/user").login(ctx, next)
  })
  .get("/user/:id", async (ctx, next) => {
    console.log(ctx.request.url)

    ctx.body = await require("./controller/user").user(ctx, next)
  })
  .post("/wx", async (ctx, next) => {
    ctx.body = await require("./controller/wx").loginOrRegister(ctx, next)
  })

router
  .post("/collection", async (ctx, next) => {
    ctx.body = await require("./controller/collection").add(ctx, next)
  })
  .delete("/collection", async (ctx, next) => {
    ctx.body = await require("./controller/collection").remove(ctx, next)
  })
  .get("/collection/:id", async (ctx, next) => {
    ctx.body = await require("./controller/collection").get(ctx, next)
  })

router
  .get("/mdn", async (ctx, next) => {
    ctx.body = await require("./controller/mdn").search(ctx, next)
  })
  .get("/mdn/article", async (ctx, next) => {
    ctx.body = await require("./controller/mdn").get(ctx, next)
  })

app.use(router.routes())

console.log(
  "\x1B[36m%s\x1B[0m",
  `🐶 app running at ${config.service.host}:${config.service.port}`
)
app.listen(3000)
